package com.gk.javaservice.util.meeting;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URL;
import java.security.cert.X509Certificate;

public class GetFileSize {

    /**
     * 配置HttpsURLConnection以忽略SSL证书和主机名验证。
     */
    public static void trustAllHttpsCertificates() throws Exception {
        // 创建一个信任所有证书的TrustManager
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() { return null; }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }
        };

        // 安装自定义的TrustManager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // 设置一个忽略主机名验证的HostnameVerifier
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
    }

    /**
     * 获取指定URL的文件大小。
     */
    public static long getFileSize(String urlString) throws Exception {
        trustAllHttpsCertificates();  // 调用信任所有证书的方法

        URL url = new URL(urlString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");

        int responseCode = connection.getResponseCode();
        if (responseCode == 200 || responseCode == 206) {
            String contentLength = connection.getHeaderField("Content-Length");
            connection.disconnect();
            return Long.parseLong(contentLength);
        } else {
            connection.disconnect();
            throw new Exception("请求失败，状态码：" + responseCode);
        }
    }


    /**
     * 将字节数转换为易于理解的单位（KB, MB, GB）。
     */
    public static String formatSize(long bytes) {
        double size = bytes;
        String unit = "B";
        if (size > 1024) {
            size /= 1024;
            unit = "KB";
        }
        if (size > 1024) {
            size /= 1024;
            unit = "MB";
        }
        if (size > 1024) {
            size /= 1024;
            unit = "GB";
        }
        return String.format("%.2f%s", size, unit);
    }

    public static void main(String[] args) {
        try {
            long fileSize = getFileSize("https://192.168.10.37:9902/record/123123123/123123123_Administrator_1741859192997.mp4");
            System.out.println("文件大小为: " + fileSize+" 字节");
            System.out.println("文件大小为: " + formatSize(fileSize));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
